<?php
$sys_pages = unserialize(SYS_PAGES);

$opts = new stdClass();
$opts->cd .=  't.sys_id = :v1';
$opts->cdv = array(':v1' => SYS_ID);
$data = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;
?>

<button onclick="Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_page');" class="pure-button pure-button-primary">New Page</button>
<div class="dd" id="nestable3"></div>

<div id="dialog_change" class="pure-form" style="display: none;" title="Change Name">
  <input type="text" id="name_change" style="width: 100%;"></input>
</div>

<script type="text/javascript">
  var __sys_pages = JSON.parse('<?php echo addslashes(json_encode($sys_pages)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __root;
  var __prev_ajax;

  $(function() {
    reset();
    render();
  });
  
  function reset() {
    __data = __data.sort(function(a, b) {
      return parseFloat(a.order, 10) > parseFloat(b.order, 10);
    });
    __root = Utils.get_root(__data);
    __root.name = 'Subcategory to...';
  };
  
  function render() {
    $('#new_name').val('');
    render_data();
    render_parent(__root, '');
  };

  function render_parent(node, prefix) {
    $('#parent').append('<option value="' + node.id + '">' + ((prefix == '') ? '' : prefix + ') ') + node.name +'</option>');
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      render_parent(itm, ((prefix == '') ? '(' : '\u2002' + prefix + '-') + (parseInt(idx, 10) + 1));
    }
  };

  function render_data() {
    var elm;
    $('#nestable3').empty();
    $('#nestable3').append('<ol id="pgol_' + __root.id + '"  class="dd-list"></ol>');
    __render_data(__root, $('#pgol_' + __root.id));
    
    var func = function(e) {
      if (e.target.id == 'nestable3') {
        update_objs();
      }
    };
    
    // activate Nestable for list 1
    $('#nestable3').nestable({
      maxDepth: 99
    }).on('change', func);
  };

  function __render_data(node, elm) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      elm.append('<li class="dd-item dd3-item" data-id="' + itm.id + '" data-name="' + itm.name + '" data-parent_id="' + itm.parent_id + '" data-order="' + itm.name + '" data-is_default="' + itm.is_default + '" data-is_visible="' + itm.is_visible + '" data-sys_id="' + itm.sys_id + '">' +
                   '<div class="dd-handle dd3-handle">&nbsp;</div>' +
                   '<div class="dd3-content">' +
                     '<a href="#" onclick="change_name(' + itm.id + ', event);">' + itm.name + '</a>' +
                     '<input type="radio" ' + ((itm.is_default == 1) ? 'checked="checked"' : '') + ' name="homepage"' + ' disabled="disabled;"></input>' + 
                     ((__sys_pages.indexOf(parseInt(itm.id, 10)) == -1) ? '<input type="checkbox" ' + ((itm.is_visible == 1) ? 'checked="checked"' : '') + ' onclick="set_visible(' + itm.id + ', this.checked ? 1 : 0);"></input>' : '') + 
                     ((__sys_pages.indexOf(parseInt(itm.id, 10)) == -1) ? '<span class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="delete_obj(' + itm.id + ');"></span>' : '') + 
                     ((__sys_pages.indexOf(parseInt(itm.id, 10)) == -1) ? '<span class="ui-button-icon-primary ui-icon ui-icon-pencil" onclick="Url.redirect(' + __redmd + ', \'' + __sys + '.php?i=' + __id + '&__file=index_page&id=' + itm.id + '\');"></span>' : '') + 
                   '</div>' + 
                   ((itm.__c.length > 0) ? '<ol id="pgol_' + itm.id + '"  class="dd-list"></ol>' : '') + 
                 '</li>');
      if (itm.__c.length > 0) {
        __render_data(itm, $('#pgol_' + itm.id));
      }
    }
  };

  //Controllers
  function update_objs() {
    if (__prev_ajax) {
      __prev_ajax.abort();
    }

    var objs = Utils.get_array($('#nestable3').nestable('serialize'), 0);
    for (var idx in __data) {
      var itm = __data[idx];
      var obj = Utils.get_by_id(itm.id, objs);
      if (obj) {
        itm.parent_id = obj.parent_id;
        itm.order = obj.order;
      }
    }
    
    __prev_ajax = Ajax.request(
      __requrl + 'update_objs',
      'reqs=' + Utils.encodeURI(JSON.stringify(__data)),
      function(rslt) {
      },
      { silent: 1 }
    );
  };

  function delete_obj(id) {
    var req = Utils.get_by_id(id, __data);
    Ajax.request(
      __requrl + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __data);
        reset();
        render();
      },
      { confirm: 1 }
    );
  };

  function set_visible(id, is_visible) {
    var req = Utils.get_by_id(id, __data);
    req.is_visible = is_visible;
    Ajax.request(
        __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  }

  function add_obj() {
    var req = {
      name: $("#new_name")[0].value,
      parent_id: $("#parent option:selected").val(),
      order: (__data.length > 0) ? parseFloat(__data[__data.length - 1].order, 10) + 1 : 1,
      file: ''
    };
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data[__data.length] = rslt;
        reset();
        render();
      },
      null
    );
  };

  function change_name(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __data);
      req.name = $('#name_change')[0].value;
      Ajax.request(
        __requrl + 'submit_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render();
          $('#dialog_change').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    var obj = Utils.get_by_id(id, __data);
    
    $('#name_change')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };
    $('#name_change').val(obj.name);
    $('#name_change').select();
  };
</script>
